<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/6
 * Time: 16:11
 */

namespace app\sgb\logic;

use think\Model;
use think\Session;

class MobileLogic extends Model
{

    const UNSET_MSG='unset';
    const SEND_SUCCESS='success';
    const SEND_FAIL='fail';
    const IS_EXPIRED='expired';
    const SESSION_MOBILE_CODE='mobile_code';
    const SUCCESS_CODE=200;
    const FAIL_CODE=4001;
    public static $code_msg="您的验证码是：%s。请不要把验证码泄露给其他人。如非本人操作，可不用理会！";
    private $api='http://106.ihuyi.cn/webservice/sms.php';
    private $api_account='cf_yunyao91';
    private $api_password = 'yy0391';
    //随机生成 验证码
    public function create_code($length = 6, $numeric = 1)
    {
        if ($numeric) {
            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        }else{
            $hash='';
            $chars='ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max=strlen($chars)-1;
            for ($i=0;$i<$length;$i++){
                $hash.=$chars[mt_rand(0,$max)];
            }
        }
        return $hash;
    }
    //发送验证码
    function sendSigleMsg($user_id , $mobile , $msg,$code){
        $MobileAuth=new MobileAuth();
        $res = $MobileAuth->send_msg($mobile, $msg);

        cache('mobile_code_'.$mobile,$code);
//        Session::set('mobile_code_'.$mobile,$code);
        if($res['status'] == 'success'){
            $this->addMsg($user_id , $mobile , $msg,self::SEND_SUCCESS);
            return true;
        }else{
            $this->addMsg($user_id , $mobile , $msg,self::SEND_FAIL,$res['msg']);
            return false;
        }
    }

    public function addMsg($user_id , $mobile , $msg ,$status,$errorMsg=""){
        if(empty($mobile) || empty($msg)){
            return false;
        }
        $data = array(
            'user_id' => $user_id,
            'mobile' => $mobile,
            'msg' => $msg,
            'create_time' => time(),
            'sent_time' => time(),
            'status' => $status,
            'error' => $errorMsg
        );
        db('mobile_messages')->insert($data);
        $aideData=[
            'mobile'=>$mobile,
            'create_time'=>time()
        ];
        $res=db('aide_mobile')->insert($aideData);
        cache('mobile_'.$mobile,$mobile,60);
        return $res ? true : false;
    }
}